﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.Query;

namespace NBusiness.Data.Providers.SqlServer.Query
{
    public class SqlInsert : SqlParameters, IInsert
    {
        private ITable _table;
        private List<IColumn> _columns = new List<IColumn>();
        private List<IEvaluatable> _parameters = new List<IEvaluatable>();

        #region IInsert Members

        public IInsert Into(ITable table, params IColumn[] columns)
        {
            if(table == null)
                throw new ArgumentNullException("table");

            _table = table;

            if(columns!=null)
                _columns.AddRange(columns);

            return this;
        }

        public IInsert Values(params object[] values)
        {
            if (values != null)
            {
                foreach (object o in values)
                {
                    IEvaluatable value = SqlEvaluatable.Coerce(o);
                    _parameters.Add(value);
                }
            }

            return this;
        }

        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            // No need for aliases in an insert statement.
            return ToSql(new SqlQueryContext(AliasAssignmentStyle.None));
        }

        public string ToSql(IQueryContext context)
        {
            StringBuilder builder = new StringBuilder("INSERT INTO ");
            builder.Append(_table.ToSql(context));

            if (_columns.Count > 0)
            {
                builder.Append(" (");
                for (int x = 0; x < _columns.Count; x++)
                {
                    if (x > 0)
                        builder.Append(", ");

                    builder.Append(_columns[x].ToSql(context));
                }
                builder.Append(")");
            }

            builder.Append(" VALUES (");
            for (int x = 0; x < _parameters.Count; x++)
            {
                if (x > 0)
                    builder.Append(", ");

                builder.Append(_parameters[x].ToSql(context));
            }
            builder.Append(")");

            return builder.ToString();
        }

        #endregion
    }
}
